package com.wangyadong.hobby.nio.charter1;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class PlainNioEchoServer {

    public void server(int port) throws IOException {
        System.out.println(" Listing for connections on port " + port);
        //服务器端
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        ServerSocket ss = socketChannel.socket();
        InetSocketAddress address = new InetSocketAddress(port);
        ss.bind(address);
        //服务器端绑定服务端地址
        socketChannel.configureBlocking(false);//设置为异步
        //打开选择器
        Selector selector = Selector.open();
        //注册选择器到socketChannel中,并设置事件类型
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            selector.select();//等待事件发生
            Set<SelectionKey> selectionKeys = selector.selectedKeys();//获取事件实例，也就是注册的实例
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel client = channel.accept();
                    System.out.println("Accepted connection from " + client);
                    client.configureBlocking(false);
                    //| 这个的作用是？
                    client.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, ByteBuffer.allocate(48));
                }
                if (key.isReadable()) {
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer attachment = (ByteBuffer) key.attachment();
                    client.read(attachment);
                }
                if (key.isWritable()) {
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer output = (ByteBuffer) key.attachment();
                    output.flip();
                    client.write(output);
                    output.compact();
                }
            }
        }
    }

    public static void main(String[] args) {
        int OP_WRITE = 1 << 2;
        int OP_READ = 1 << 0;
        System.out.println("==");
    }
}
